package com.login_1.util;

import com.alibaba.druid.pool.DruidDataSourceFactory;

import javax.sql.DataSource;
import java.sql.Connection;
import java.sql.PreparedStatement;
import java.sql.ResultSet;
import java.util.Properties;

public class DruidUtils {
    private static DataSource dataSource;

    static {
        //创建数据库连接池对象
        try {
            Properties p = new Properties();
            p.load(DruidUtils.class.getClassLoader().getResourceAsStream("druid.properties"));
            dataSource = DruidDataSourceFactory.createDataSource(p);
            System.out.println("准备好了......");
        } catch (Exception e) {
            System.out.println("创建数据库连接池对象失败~");
        }
    }

    //获取数据库连接池对象方法
    public static DataSource getDataSource() {
        return dataSource;
    }

    //获取数据库连接对象方法
    public static Connection getConnection() throws Exception {
        return dataSource.getConnection();
    }

    //归还数据库连接对象方法
    public static void close(Connection conn, PreparedStatement ps) throws Exception {
        close(conn, ps, null);
    }

    //归还连接方法
    public static void close(Connection conn, PreparedStatement ps, ResultSet resultSet) throws Exception {
        if (conn != null) {
            conn.close();//这里归还的意思
        }

        if (ps != null) {
            ps.close();//释放资源
        }

        if (resultSet != null) {
            resultSet.close();//释放资源
        }
    }
}
